﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Collections.Specialized;
using DWF.Studio.Share.Serialization;
using DWF.Studio.NuGetManagement;
using DWF.Studio.Share.Utils;

namespace DWF.Studio.Services
{
    internal class ConfigService : IConfigService
    {
        private static readonly object _obj = new object();

        private IAppService _appService = null;

        public ConfigService()
        {
            _appService = AppService.Instance;
        }

        /* Oliver 2021-06-16 日志输出默认到文件 begin */
        private static SysConfig _sysConfig;
        internal static SysConfig CurrentSysConfig
        {
            get
            {
                return _sysConfig ?? null;
            }
            private set
            {
                _sysConfig = value;
            }
        }
        /* Oliver 2021-06-16 日志输出默认到文件 end */


        /// <summary>
        /// 加载系统配置信息
        /// </summary>
        /// <returns></returns>
        public SysConfig LoadSysConfig()
        {
            lock (_obj)
            {
                var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var filePath = System.IO.Path.Combine(localAppData, StaticResource.ProcessGo, StaticResource.Studio, StaticResource.SysConfig);
                var appConfig = LoadAppConfig();
                SysConfig sysConfig = null;
                if (FileHelper.CheckFileExisting(filePath))//检查配置文件是否存在，如果存在这加载，否者新建。
                {
                    sysConfig = YamlHelper.Load<SysConfig>(filePath);
                    if (String.IsNullOrWhiteSpace(sysConfig.WorkSpace))
                    {
                        sysConfig.WorkSpace = getDefaultWorkSpacePath();
                        SaveSysConfig(sysConfig);

                        if (!FileHelper.CheckFolderExisting(sysConfig.WorkSpace))
                        {
                            FileHelper.CreateFolder(sysConfig.WorkSpace);
                        }
                    }

                    if (String.IsNullOrWhiteSpace(sysConfig.UpgradeUri))
                    {
                        sysConfig.UpgradeUri = appConfig.UpgradeUri;
                        SaveSysConfig(sysConfig);
                    }
                    if (sysConfig.PackageUris == null)//如果为空则添加默认地址，老版本配置文件没有该字段是这个情况
                    {
                        var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
                        List<PackageSourceUri> packagelist = new List<PackageSourceUri>
                        {
                            new PackageSourceUri("Local", "Local", System.IO.Path.Combine(baseDirectory, StaticResource.Packages), true, true),
                            new PackageSourceUri("Official", "Official", ConfigurationManager.AppSettings["OfficialPackageLink"], true, true)
                        };
                        sysConfig.PackageUris = packagelist;
                        SaveSysConfig(sysConfig);
                    }
                    else if (sysConfig.PackageUris.Where(o => o.DisplayName == "Official" && o.IsDefault == true).Count() == 0)
                    {
                        PackageSourceUri packagelist = new PackageSourceUri("Official", "Official", ConfigurationManager.AppSettings["OfficialPackageLink"], true, true);
                        sysConfig.PackageUris.Add(packagelist);
                        SaveSysConfig(sysConfig);
                    }
                    if (sysConfig.AssetsUri == null)//如果为空则添加默认地址，老版本配置文件没有该字段是这个情况
                    {
                        sysConfig.AssetsUri = "";
                        SaveSysConfig(sysConfig);
                    }
                }
                else
                {
                    sysConfig = new SysConfig();
                    var workSpace = getDefaultWorkSpacePath();
                    if (!FileHelper.CheckFolderExisting(workSpace))
                    {
                        FileHelper.CreateFolder(workSpace);
                        sysConfig.WorkSpace = workSpace;
                    }
                    sysConfig.WorkSpace = workSpace;
                    sysConfig.IsAutoSave = false;
                    sysConfig.PackageUri = appConfig.PackageUri;
                    sysConfig.PackageUris = appConfig.PackageUris;
                    sysConfig.FlatformUri = appConfig.FlatformUri;
                    sysConfig.UpgradeUri = appConfig.UpgradeUri;
                    sysConfig.AssetsUri = "";
                    sysConfig.LangugeId = _appService.GetCurrentThreadLanguageId();
                    sysConfig.IsLogToFile = false;  //Oliver 2021-06-16 默认执行日志不保存到文件
                    sysConfig.IsConsoleOutToFile = false;  //Oliver 2021-06-17 默认执行输出不保存到文件
                    sysConfig.IsSilentExecution = false;  //Oliver 2021-06-25 默认不执行静默输出
                    sysConfig.IsDebugShowWindow = false;  //Carl 2021-06-28 运行时最小化窗口，命中断点还原窗口

                    SaveSysConfig(sysConfig);
                }

                CurrentSysConfig = sysConfig;  //Oliver 2021-06-16 日志输出默认到文件
                return sysConfig;
            }
        }

        private string getDefaultWorkSpacePath()
        {
            String myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var workSpace = System.IO.Path.Combine(myDocumentsPath, StaticResource.ProcessGo);

            return workSpace;
        }

        /// <summary>
        /// 保存系统配置信息
        /// </summary>
        public void SaveSysConfig(SysConfig sysConfig)
        {
            lock (_obj)
            {
                var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var sysPath = System.IO.Path.Combine(localAppData, StaticResource.ProcessGo, StaticResource.Studio);

                if (!FileHelper.CheckFolderExisting(sysPath))
                {
                    FileHelper.CreateFolder(sysPath);
                }

                var filePath = System.IO.Path.Combine(sysPath, StaticResource.SysConfig);

                YamlHelper.Save(sysConfig, filePath);
      
                CurrentSysConfig = sysConfig;  //Oliver 2021-06-16 执行日志保存到文件相关
            }
        }

        public AppConfig LoadAppConfig()
        {
            var appConfig = new AppConfig();

            appConfig.LocalRobotIP = ConfigurationManager.AppSettings["LocalRobotIP"];
            appConfig.LocalRobotPort = ConfigurationManager.AppSettings["LocalRobotPort"];
            appConfig.PackageUri = ConfigurationManager.AppSettings["PackageUri"];
            appConfig.PackageUris = new List<PackageSourceUri>
            {
                new PackageSourceUri("Local", "Local", System.IO.Path.Combine(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName, StaticResource.Packages), true, true),
                new PackageSourceUri("Official", "Official", ConfigurationManager.AppSettings["OfficialPackageLink"], true, true)
            };
               
            appConfig.FlatformUri = ConfigurationManager.AppSettings["FlatformUri"];
            appConfig.UpgradeUri = ConfigurationManager.AppSettings["UpgradeUri"];
            
            appConfig.OfficialWebsite = ConfigurationManager.AppSettings["OfficialWebsite"];
            appConfig.ProcessgoWebsite = ConfigurationManager.AppSettings["ProcessgoWebsite"];
            appConfig.OfficialEMail = ConfigurationManager.AppSettings["OfficialEMail"];
            appConfig.ContactNumber = ConfigurationManager.AppSettings["ContactNumber"];

            return appConfig;
        }

        public NameValueCollection GetProjectDependencies()
        {
            var dependencies = (NameValueCollection)ConfigurationManager.GetSection("projectDependencies");

            return dependencies;
        }
    }
}
